package com.controller;

import com.entity.Notice;
import com.util.DataSourceUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;

@WebServlet("/getnotice")
public class GetNoticeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException
    {
        Notice notice=new Notice();
        String sql="select * from Notices where NID=?";
        String sql2="select COUNT(*) from Notices";
        int count=0;
        try (Connection con = DataSourceUtils.getConnection();
             PreparedStatement ps=con.prepareStatement(sql)){
            ps.setString(1,req.getParameter("nid"));
            try(ResultSet rs=ps.executeQuery();
                PreparedStatement ps2=con.prepareStatement(sql2);
                ResultSet rs2 =ps2.executeQuery())
            {
                if (rs2.next()) {
                    count = rs2.getInt(1); // 获取查询结果
                }
                rs.next();
                notice.setNid(rs.getString("NID"));
                notice.setTitle(rs.getString("Title"));
                notice.setAuthor(rs.getString("Author"));
                notice.setDateTime(rs.getObject("Date", LocalDateTime.class));
                notice.setContent(rs.getString("Content"));
                notice.setImageurl(rs.getString("ImageURL"));
            }
        }
        catch (SQLException e)
        {
            throw new RuntimeException(e);
        }
        req.setAttribute("notice",notice);
        req.setAttribute("count", count);
        req.getRequestDispatcher("/WEB-INF/jsp/notice.jsp").forward(req,resp);
    }

    //@Override
    //protected void doPost(HttpServletRequest req,HttpServletResponse resp)
    //{
    //
    //}
}
